package com.kit.data.kitopeso.tools;

import android.util.Base64;

import java.nio.charset.StandardCharsets;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESCryptUtilJar {

    private static final String AES_NAME = "AES";

    private static final String AES_MODE = "AES/CBC/PKCS5Padding";


    private static final String AES_KEY = "kitopesocw22yu3b";

    private static final String AES_IV = "kitopesocw88yu3b";



    public static String encrypt(String key, String iv, String message) {
        try {
            Cipher cipher = Cipher.getInstance(AES_MODE);
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_NAME);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] encrypted = cipher.doFinal(message.getBytes(StandardCharsets.UTF_8));
            return Base64.encodeToString(encrypted, Base64.DEFAULT | Base64.NO_WRAP);
        } catch (Exception ignored) {
        }
        return "";
    }


    public static String encryptDefault(String message) {
        return encrypt(AES_KEY, AES_IV, message);
    }


    public static String decrypt(String key, String iv, String encryptedMessage) {
        try {
            Cipher cipher = Cipher.getInstance(AES_MODE);
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_NAME);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] encryptedBytes = Base64.decode(encryptedMessage, Base64.DEFAULT | Base64.NO_WRAP);
            if (encryptedBytes != null) {
                byte[] decrypted = cipher.doFinal(encryptedBytes);
                return new String(decrypted, StandardCharsets.UTF_8);
            }
            return null;
        } catch (Exception ignored) {
        }
        return "";
    }


    public static String decryptDefault(String encryptedMessage) {
        return decrypt(AES_KEY, AES_IV, encryptedMessage);
    }

}
